package com.yhj.controller;

import com.yhj.model.JWTUtil;
import com.yhj.model.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

/**
 * @author yaohj
 * @date 2024年12月11日 13:25
 */
@RestController
@RequestMapping("security")
@Slf4j
public class SecurityLoginController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Resource
    private JWTUtil jwtUtil;

    @Resource
    private RedisTemplate redisTemplate;


    @GetMapping("/login")
    public String securityLogin(String username,String password){
        UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username,password);
        // 使用authenticationManager调用loadUserByUsername获取数据库中的用户信息,
        Authentication authentication = authenticationManager.authenticate(authToken);
        if(authentication == null) {
            throw new RuntimeException("登录失败啦呀");
        }

        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        StringBuilder permissions = new StringBuilder();
        for (GrantedAuthority authority : authorities) {
            permissions.append(authority.getAuthority()).append(" ");
        }
        log.info(permissions.toString());

        //获取符合security规范的User
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();

        String token = jwtUtil.createToken(securityUser.getUser());
        //redis过期时间可以比token久一点用户后续的更新token过期时间
        redisTemplate.opsForValue().set("sys:user:token"+token,token, 2, TimeUnit.MINUTES);
        //redis过期时间可以比token久一点用户后续的更新token过期时间
        redisTemplate.opsForHash().put("sys:user", token, securityUser.getUser() );
        return token;
    }
}
